package com.tycmc.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.tycmc.common.util.Property;

public class CreateRabbitMQConnection {
	// 连接器
	private static Connection connection = null;

	/*
	 * 获取连接频道 用于发送消息
	 */
	public static Channel getChannel()  {
		Channel channel = null;
		try {
			if (connection == null) {
                connection = init();
            }
			channel = connection.createChannel();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return channel;
	}

	private synchronized static Connection init() {
		ConnectionFactory factory;
		try {
			factory = new ConnectionFactory();
			String[] property = Property.getProperty("rabbitmq.host").split(",");
			for (String s : property) {
                factory.setHost(s);
            }
			factory.setUsername(Property.getProperty("rabbitmq.username"));
			factory.setPassword(Property.getProperty("rabbitmq.password"));
			factory.setPort(Integer.parseInt(Property.getProperty("rabbitmq.port")));
			factory.setVirtualHost(Property.getProperty("rabbitmq.virtualhost"));
			return factory.newConnection(); // 创建一个新的连接
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
